package com.msoe.client.panels.eventhandlers;

import java.util.HashMap;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Widget;
import com.msoe.client.Server;
import com.msoe.client.panels.AccountSettings;
import com.msoe.client.panels.MessageBox;

public class AccountSettingsEventHandler implements ClickListener{

	private AccountSettings acc;
	
	public AccountSettingsEventHandler(AccountSettings account){
		acc = account;
	}
	
	public void onClick(Widget sender) {
		
		if(sender instanceof Button){
			Button clickedButton = ((Button) sender);
			if(clickedButton.getText().equals("Save Changes"))
			{
				HashMap<String, String> fields = acc.getFields();
				if(validateFields(fields)){
					submit(fields);
				}
			}
		}
	}
	
	private boolean validateFields(HashMap<String, String> fields){
		boolean retVal = true;
		String failMsg = "";
		
		//password contains characters from ascii 33(!) to 126(~)
		if(!fields.get("password").matches("[!-~]+")){
			failMsg += "Invalid password.\n";
			retVal = false;
		}
		
		//password contains characters from ascii 33(!) to 126(~)
		if(!fields.get("new").matches("[!-~]+")){
			failMsg += "Invalid new password.\n";
			retVal = false;
		}
		
		
		if(!fields.get("confirm").equals(fields.get("new"))){
			failMsg += "Passwords do not match.\n";
			retVal = false;
		}
		
		if(!failMsg.equals("")){
			MessageBox.showMessageDialog("Settings Change", failMsg);
		}
		
		return retVal;
	}

	private void submit(final HashMap<String, String> fields){
		AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>()
		{
			public void onSuccess(Boolean result)
			{
				if(result)
				{
					MessageBox.showMessageDialog("Success!", "You have successfully changed your password!.");
				}
				else
				{
					MessageBox.showMessageDialog("Error!", "There was a problem changing your password.");
				}
			}

			public void onFailure(Throwable ex)
			{
				Window.alert(ex.getMessage());
			}
		};
		
		Server.getInstance().getServer().changePassword(acc.getSession().getUser(), fields.get("new"), callback);
	}
	
}
